//
//
//

#include <NewSoftSerial.h>

const int ledPin     = 13;
const int phoneTxPin = 3;
const int phoneRxPin = 2;

NewSoftSerial phoneSerial =  NewSoftSerial(phoneRxPin, phoneTxPin);


int endbyte = 35;          //end of serial data  
long previousMillis = 0;   // will store last time data was sent to serial port
long interval = 15000;     // interval at which to send data (milliseconds)

// theurl is what the phone will use to connect to a website
// the format is domain,/path/filename.ext -- Note the comma!!
// make sure to change the server and page path to match your server adddress
char theurl[] = "todbot.com,/tst/color.txt";


char serInStr[slen];            // array to hold the incoming serial string 
boolean serverinfo = false;     // variable to define initial settings

void setup()  {
  
  pinMode(ledPin, OUTPUT);
  
  // set the data rate for the main serial port
  // 9600 is just the value I used, depending on your phone (or other device)
  // you connect to, you may want to bump it up
  phoneSerial.begin(9600);
  Serial.begin(9600);
  Serial.println("iDenTest ready");

}

void loop()
{
  // start the count down
  if (millis() - previousMillis > interval) { // if the end has been met
    previousMillis = millis();                // zero the counter
    
    // send sersor data to serial followed by endchar
    // if you have anything to send to the web, this is where to place it.
    // you have to compose the whole query string and end it with the endbyte #
    // in this sample I'm just sending the amount of milsecs passed since the 
    // beginning. . . if you have nothing to pass and just want to fetch
    // data from a webpage, just pass the endbyte along.
    
    // for every request we send theurl, and anything else we got.
    phoneSerial.print(theurl);
   
   // to pass anything else, use ",varcname=value&varname1=value1 etc 
    phoneSerial.print(",millis="); 
    phoneSerial.print(previousMillis); 
    
    // we end the message with the endbyte
    phoneSerial.print(endbyte, BYTE); 
    
  } 
  else {   
    // if the count down is still running
    // we just keep watching the serial port 
    int datalength = readPhoneSerialString();
    // if we get a # on the serial and server info (theurl) has not been sent
    // we need to tell the phone where to send the data 
    
     if (datalength > 0) {
       Serial.println( serInStr );
         writetolcd(datalenght);
    }
  }
}


int readPhoneSerialString()
{
  int i=0;
  if(!phoneSerial.available()) {
    return -1;
  }
  int c = 0;
  // we wait on the serial port while it is open 
  // and not too long 
  // we append each byte received to serInStr
  // in the end we return the lenght of the data received
  while(phoneSerial.available() && i < slen-1) {
    c = phoneSerial.read();
    serInStr[i++] = c;
  }
  serInStr[i] = 0; // mark end of string

  return i;
}


